﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ATM_Banking_Service.DAO
{
    internal class SercurityDAO
    {
        public string CreateToken(string id)
        {
            ATMServiceEntities context;
            using (context = Common.Utils.GetObjectContext())
            {
                string token = Guid.NewGuid().ToString();
                DateTime begintime = DateTime.Now;
                DateTime endtime = begintime.AddMinutes(15);
                var customer = new Sercurity
                                   {CustomerId = id, CustomerToken = token, Begintime = begintime, Endtime = endtime, Status = "Active"};
                context.Sercurity.Add(customer);
                context.SaveChanges();
                return token;
            }
        }

        public bool ValidateToken(string token)
        {
            ATMServiceEntities context;
            DateTime timeNow = DateTime.Now;
            using (context = Common.Utils.GetObjectContext())
            {
                var result =
                    context.Sercurity.ToList().Where(sercurity => sercurity.CustomerToken.Equals(token)).Any(
                        sercurity => sercurity.Endtime < timeNow);
                
                if (result != null)
                {
                    return false;
                }
                return true;
            }
        }

        public string GetIdByToken(string token)
        {
            ATMServiceEntities context;
            using (context = Common.Utils.GetObjectContext())
             {
                 var result = context.Sercurity.FirstOrDefault(sercurity => sercurity.CustomerToken.Equals(token));
                 if (result==null)
                 {
                     return "";
                 }
                 string customerId = result.CustomerId;
                 return customerId;
             }
        }
    }
}
